package com.aptemo.webetek.client.widgets.players;

import com.aptemo.webetek.client.WebetekUserServiceAsync;
import com.aptemo.webetek.client.commands.GotAsynchCallback;
import com.aptemo.webetek.client.commands.impl.GetPlayerDetailsAction;
import com.aptemo.webetek.client.commands.impl.ModifyPlayerAction;
import com.aptemo.webetek.client.commands.impl.PaymentAction;
import com.aptemo.webetek.client.commands.impl.RemovePlayerAction;
import com.aptemo.webetek.client.commands.responses.ResponseStatus;
import com.aptemo.webetek.client.enums.EnumPaymentType;
import com.aptemo.webetek.client.enums.EnumUserRole;
import com.aptemo.webetek.client.enums.EnumUserStatus;
import com.aptemo.webetek.client.events.DecisionEvent;
import com.aptemo.webetek.client.events.DecisionHandler;
import com.aptemo.webetek.client.events.HasDecisionHandlers;
import com.aptemo.webetek.client.events.PlayerListUpdatedEvent;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.client.mvp.BaseDisplay;
import com.aptemo.webetek.client.mvp.BasePresenter;
import com.aptemo.webetek.shared.PaymentBean;
import com.aptemo.webetek.shared.UserBean;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;

public class PlayerResumePresenter implements BasePresenter, ClickHandler, DecisionHandler
{

	interface Display extends BaseDisplay
	{
		HasClickHandlers getSaveButton();

		HasText getInfoField();

		HasText getTitleField();

		HasText getEmailField();

		HasText getBalanceField();

		void setRoleField(EnumUserRole role);

		void setStatusField(EnumUserStatus status);

		EnumUserRole getSelectedRole();

		EnumUserStatus getSelectedStatus();

		HasClickHandlers getNewPaymentButton();

		HasValue<String> getPaymentAmountField();

		HasDecisionHandlers getDeleteConfirmation();

		void hideDeleteDialog();

		String translate(String key);
	}

	private Display					display;
	private WebetekUserServiceAsync	rpcService;
	private HandlerManager			eventbus;
	private String					id;
	private String					teamId;

	public PlayerResumePresenter(Display view, HandlerManager eventBus, WebetekUserServiceAsync rpcService, String id, String teamId)
	{
		this.display = view;
		this.rpcService = rpcService;
		this.id = id;
		this.teamId = teamId;
		this.eventbus = eventBus;
	}

	@Override
	public void go(HasWidgets container)
	{
		bind();

		container.clear();
		container.add(display.getDisplay());

		// 
		loadUsers();
	}

	private void bind()
	{
		display.getSaveButton().addClickHandler(this);

		display.getDeleteConfirmation().addDecisionHandler(this);

		display.getNewPaymentButton().addClickHandler(this);

	}

	private void loadUsers()
	{
		display.getInfoField().setText(display.translate("loading"));

		GetPlayerDetailsAction action = new GetPlayerDetailsAction(this.id);
		rpcService.invoke(action, new GotAsynchCallback<UserBean>()
		{

			@Override
			public void onError(String message, EErrorCodes code)
			{
				display.getInfoField().setText("Error getting players: " + message);
			}

			@Override
			public void onSuccess(UserBean result)
			{
				display.getInfoField().setText("");

				display.getTitleField().setText(result.getEmail());

				display.getEmailField().setText(result.getEmail());

				display.setRoleField(result.getRole());

				display.setStatusField(result.getStatus());

				display.getBalanceField().setText(result.getBalance() + "");
			}
		});

	}

	protected void deletePlayer()
	{
		RemovePlayerAction action = new RemovePlayerAction(id, "");
		rpcService.invoke(action, new GotAsynchCallback<ResponseStatus>()
		{

			@Override
			public void onSuccess(ResponseStatus result)
			{
				display.getInfoField().setText(display.translate("playerRemoved"));
				eventbus.fireEvent(new PlayerListUpdatedEvent(teamId));

				display.hideDeleteDialog();

				// display.getDisplay().getParent().removeFromParent();
			}

			@Override
			public void onError(String message, EErrorCodes code)
			{
				// TODO Auto-generated method stub

			}
		});
	}

	protected void savePlayer()
	{
		UserBean user = new UserBean(display.getEmailField().getText());
		user.setKey(id);
		user.setRole(display.getSelectedRole());
		user.setStatus(display.getSelectedStatus());
		// convert...
		Double bal = Double.parseDouble(display.getBalanceField().getText());
		user.setBalance(bal);

		display.getInfoField().setText(display.translate("saving"));

		ModifyPlayerAction action = new ModifyPlayerAction(user, teamId);
		rpcService.invoke(action, new GotAsynchCallback<UserBean>()
		{

			@Override
			public void onError(String message, EErrorCodes code)
			{
				display.getInfoField().setText(display.translate("errorModify") + ": " + message);
			}

			@Override
			public void onSuccess(UserBean result)
			{
				display.getInfoField().setText("Player data modified!");

				// loadUsers();
				eventbus.fireEvent(new PlayerListUpdatedEvent(teamId));
			}
		});
	}

	@Override
	public void onClick(ClickEvent event)
	{
		if (event.getSource() == display.getSaveButton())
		{
			savePlayer();
		}
		else if (event.getSource() == display.getNewPaymentButton())
		{
			makePayment();
		}
	}

	private void makePayment()
	{
		double amount = 0.0;

		String am = display.getPaymentAmountField().getValue();
		try
		{
			amount = Double.parseDouble(am);
		}
		catch (NumberFormatException e)
		{
			display.getInfoField().setText(display.translate("wrongNumberFormat"));
			return;
		}

		// check amount...
		if (amount <= 0.0)
		{
			display.getInfoField().setText(display.translate("wrongNumberFormat"));
			return;
		}

		display.getInfoField().setText(display.translate("saving"));

		PaymentAction action = new PaymentAction(id, teamId, amount, EnumPaymentType.PAYMENT);
		rpcService.invoke(action, new GotAsynchCallback<PaymentBean>()
		{

			@Override
			public void onError(String message, EErrorCodes code)
			{
				display.getInfoField().setText(message);
				display.getPaymentAmountField().setValue("");
			}

			@Override
			public void onSuccess(PaymentBean result)
			{
				display.getInfoField().setText(display.translate("paymentSuccess"));

				// display.getBalanceField().setText(result.getBalance() + "");
				display.getPaymentAmountField().setValue("");

				// Update...
				eventbus.fireEvent(new PlayerListUpdatedEvent(teamId));
			}
		});

	}

	@Override
	public void onConfirmation(DecisionEvent event)
	{
		if (event.getSource() == display.getDeleteConfirmation())
		{
			deletePlayer();
		}
	}

}
